package com.zprmb.udzt;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.MyReceiver;
import com.zprmb.udzt.util.Regular;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.HttpClientStack;
import com.zprmb.udzt.vo.toolbox.HttpStack;
import com.zprmb.udzt.vo.toolbox.ImageRequest;
import com.zprmb.udzt.vo.toolbox.Volley;
/**
 * 绑卡界面
 * @author shenshao
 *
 */
public class BankCardActivity extends BaseActivity implements OnClickListener{
	private EditText et_real_name,et_real_idcard,et_card_num,et_user_phone;
	private RelativeLayout li_stand_bank;
	private Button btn_bindcard;
	private ImageView img_back,img_bank;
	private String bankNo,name,idcard,what_bank;
	private boolean flag;
	private TextView tv_bank,tv_bind_info,tv_title;
	private RequestQueue mQueue;
	private CheckBox checkBox;
	private int who,isbank;
	private String logourl,status;
	private RelativeLayout rl_back;
	private TextView tv_customer,user_status;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bind_bankcard);
		BbtApplication.getInstance().addActvity(this);
		DefaultHttpClient httpclient = new DefaultHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        httpclient.setCookieStore(cookieStore);
        HttpStack httpStack = new HttpClientStack(httpclient);
        mQueue = Volley.newRequestQueue(this, httpStack);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("exit");       
        this.registerReceiver(myReceiver,mFilter);
        isbank=getIntent().getIntExtra("isbank", 0);
        user_status=(TextView)findViewById(R.id.user_status);
		et_real_name=(EditText)findViewById(R.id.real_name);
		tv_title=(TextView)findViewById(R.id.title);
		et_real_idcard=(EditText)findViewById(R.id.real_idcard);
		et_card_num=(EditText)findViewById(R.id.card_num);
		checkBox=(CheckBox)findViewById(R.id.check);
		et_user_phone=(EditText)findViewById(R.id.user_phone);
		img_back=(ImageView)findViewById(R.id.img_back);
		tv_bank=(TextView)findViewById(R.id.tv_bank);
		img_bank=(ImageView)findViewById(R.id.img_bank);
		tv_bind_info=(TextView)findViewById(R.id.bind_info);
		rl_back=(RelativeLayout)findViewById(R.id.rl_back);
		tv_customer=(TextView)findViewById(R.id.enterprise_tel);
		tv_customer.setOnClickListener(this);
		rl_back.setOnClickListener(this);
		who=getIntent().getIntExtra("who", 0);
		
		tv_bind_info.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(BankCardActivity.this,BindBankInfo.class);
				startActivity(intent);
			}
		});
		img_back.setOnClickListener(this);
		li_stand_bank=(RelativeLayout)findViewById(R.id.li_stand_bank);
		 btn_bindcard=(Button)findViewById(R.id.bind_bankcard);
		 btn_bindcard.setOnClickListener(this);
		 li_stand_bank.setOnClickListener(this);
		 if(isbank==1){
	        	btn_bindcard.setText("认证确认");
	        	tv_title.setText("认证确认");
	        }else{
	        	btn_bindcard.setText("绑定银行卡");
	        	tv_title.setText("绑定银行卡");
	        }
		 checkBox.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			  if(checkBox.isChecked()){
				  btn_bindcard.setBackgroundResource(R.drawable.my_button);
				  btn_bindcard.setEnabled(true);
			  }else{
				  btn_bindcard.setBackgroundResource(R.drawable.btn_unclick);
				  btn_bindcard.setEnabled(false);
			  }
			}
		});
		 if(isbank==1){
	        	et_card_num.setText(getIntent().getStringExtra("bankcard"));
	        	img_bank.setVisibility(View.VISIBLE);
	        	logourl=getIntent().getStringExtra("logourl");
	        	BbtApplication.getInstance().display(Constant.URL+logourl, img_bank);
	        	tv_bank.setText(getIntent().getStringExtra("banknameCn"));
	        	bankNo=getIntent().getStringExtra("banknameEn");
	        	status=getIntent().getStringExtra("status");
	        	et_card_num.setEnabled(false);
	        	li_stand_bank.setEnabled(false);
	        }else{
	        	et_card_num.setText("");
	        	img_bank.setVisibility(View.GONE);
	        	et_card_num.setEnabled(true);
	        }
		initData();
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}
	 MyReceiver myReceiver = new MyReceiver(){
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            finish();
	        }
	    };
	private void initData() {
		// TODO Auto-generated method stub
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				LogUtils.e("ss", jsonObject.toString());
				JSONObject json1=jsonObject.optJSONObject("data");
				flag=json1.optBoolean("nameAuth");
				if(json1.optBoolean("nameAuth")){
					et_real_name.setText(json1.optString("userName"));
					et_real_idcard.setText(json1.optString("idNumber"));
					name=json1.optString("userName");
					idcard=json1.optString("idN");
					et_real_name.setEnabled(false);
					et_real_idcard.setEnabled(false);
					user_status.setText("持卡人信息");
				}else{
					user_status.setText("实名认证");
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setHeaders("token", getToken());
		volleryUtil.setShow(true);		
		volleryUtil.execute(BankCardActivity.this, Constant.URL+"/api/v5/user/userInfo", "");
	}
	private void bindcard() {
		// TODO Auto-generated method stub
		AjaxParams params=new AjaxParams();
		if(flag){
			try {
				params.put("name", URLEncoder.encode(name,"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			params.put("name", name);
			params.put("idNumber",idcard);
		}else{
			
			try {
				params.put("name", URLEncoder.encode(et_real_name.getText().toString(),"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			params.put("name", et_real_name.getText().toString());
			params.put("idNumber", et_real_idcard.getText().toString());
		}
if(isbank==1){
	params.put("bank", bankNo);
	params.put("cardNo", et_card_num.getText().toString());
	params.put("mobile", et_user_phone.getText().toString());
	params.put("isRead", "1");	
	params.put("bankMobileStatus", status);	
	
		}else{
			params.put("bank", bankNo);
			params.put("cardNo", et_card_num.getText().toString());
			params.put("mobile", et_user_phone.getText().toString());
			params.put("isRead", "1");	
			
		}
		
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				LogUtils.e("num", jsonObject.toString());
				if(jsonObject.optInt("success")==1){
					Intent intent1=new Intent(BankCardActivity.this,Message_dialog.class);
					intent1.putExtra("user_phone", et_user_phone.getText().toString());
					intent1.putExtra("flag", flag);
					intent1.putExtra("who", who);
					intent1.putExtra("isbank", isbank);
					startActivity(intent1);
					
					
				}else {
					if (jsonObject.optString("comment").equals("please login")) {
						Intent intent = new Intent(BankCardActivity.this,LoginActivity.class);
						startActivity(intent);
					}else{
						Toast.makeText(BankCardActivity.this, jsonObject.optString("comment"), 2000).show();
					}
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};  
		volleryUtil.setHeaders("token", getToken());
		volleryUtil.setRequestMethod(1);
		volleryUtil.setShow(true);
		
		volleryUtil.execute(BankCardActivity.this, Constant.URL+"/api/v5/account/bankcard/bind/request", "?"+params.toString());
		Log.e("参数", params.toString());
	}
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if(!(arg2==null)){
			bankNo=arg2.getStringExtra("bank");
			img_bank.setVisibility(View.VISIBLE);
			loadimg(arg2.getStringExtra("img"));
			
			tv_bank.setText(arg2.getStringExtra("name"));
			
		} 
			
	}
private void	loadimg(String url){
	ImageRequest imageRequest = new ImageRequest(  
			Constant.URL+url,  
	        new Response.Listener<Bitmap>() {  
	            @Override  
	            public void onResponse(Bitmap response) {  
	                img_bank.setImageBitmap(response);  
	            }  
	        }, 0, 0, Config.RGB_565, new Response.ErrorListener() {  
	            @Override  
	            public void onErrorResponse(VolleyError error) {  
	            	img_bank.setImageResource(R.drawable.ic_launcher);  
	            }  
	        }); 
	mQueue.add(imageRequest);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.li_stand_bank:
			
			Intent intent=new Intent(BankCardActivity.this,Standby_bank.class);
			intent.putExtra("bind", 1);
			intent.putExtra("bankNo", "1");
			startActivityForResult(intent, 1);
			break;
		case R.id.bind_bankcard:
			if(et_real_name.getText().toString().equals("")){
				Toast.makeText(BankCardActivity.this, "请输入真实姓名", 2000).show();
				return;
			}
			if(et_real_idcard.getText().toString().equals("")){
				Toast.makeText(BankCardActivity.this, "请输入真实身份证号码", 2000).show();
				return;
			}
			if(et_user_phone.getText().toString().equals("")){
				Toast.makeText(BankCardActivity.this, "请输入银行预留手机号", 2000).show();
				return;
			}
			if(!Regular.isMobileNO(et_user_phone.getText().toString())){
				Toast.makeText(BankCardActivity.this, "请输入正确的手机号码",2000).show();
				return;
			}
			if(et_card_num.getText().toString().equals("")){
				Toast.makeText(BankCardActivity.this, "请输入银行卡号", 2000).show();
				return;
			}
			if(bankNo==null){
				Toast.makeText(BankCardActivity.this, "请选择银行", 2000).show();
				return;
			}
			
				
				bindcard();
			
			
			break;
		case R.id.img_back:
			finish();
			break;
		case R.id.rl_back:
			finish();
			break;
		case R.id.enterprise_tel:
			BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
			break;
		}
	}
	

}
